package com.menker.app.ui.main;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.FadeEnter.FadeEnter;
import com.flyco.animation.FadeExit.FadeExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.menker.app.Constants;
import com.menker.app.MyApp;
import com.menker.app.R;
import com.menker.app.biz.CurrentUser;
import com.menker.app.biz.ItemInfo;
import com.menker.app.biz.WebPageInfo;
import com.menker.app.common.DoubleClickExitDetector;
import com.menker.app.common.SharedPreferencesHelper;
import com.menker.app.common.Utils;
import com.menker.app.dao.ItemDAO;
import com.menker.app.di.DaggerScope;
import com.menker.app.di.Injector;
import com.menker.app.rest.ApiHelper;
import com.menker.app.rest.result.ApiResult;
import com.menker.app.rest.result.AppInfo;
import com.menker.app.rest.result.MsgInfo;
import com.menker.app.util.DialogUtils;
import com.menker.app.util.ImageFileUtils;
import com.menker.app.util.IntentUtils;
import com.menker.app.webview.WebViewManager;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.litepal.util.Const;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import myandroid.library.util.ApplicationHelper;
import retrofit2.http.Body;
import rx.Subscriber;

import static com.menker.app.Constants.API.ENDPOINT;

/**
 * @author J.Huang
 * @version 1.0
 */
@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(MainActivity.class)
@EActivity(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {

    private static final int APP_PERMISSION = 100;

    @Inject
    ApiHelper mApiHelper;
    @Inject
    CurrentUser mCurrentUser;
    @Inject
    SharedPreferencesHelper mSharedPreferencesHelper;

    @Inject
    DoubleClickExitDetector mDoubleClickExitDetector;

    @ViewById(R.id.layout_main)
    LinearLayout mMainLayout;
    @ViewById(R.id.layout_splash)
    RelativeLayout mSplashLayout;
    @ViewById(R.id.activity_main_web)
    BridgeWebView mWebView;

    @StringRes(R.string.error_api)
    String mStrErrorApi;

    private boolean updatePermissionTip = true;
    private boolean phonePermissionTip = true;

    public LocationClient locationClient;

    private NormalDialog mDownloadPermissionDialog;
    private NormalDialog mPhonePermissionDialog;

    private boolean splashShow = true;
    private boolean intentByLogin = false;

    private static final int DELAY_CHECK_PHONE = 1111;
    private static final int DELAY_TO_NEXT = 1112;

    @AfterInject
    void initDI() {
        Intent intent = getIntent();

        if (intent != null && intent.getExtras() != null) {
            intentByLogin = intent.getBooleanExtra("byLogin", false);
        }

    }

    @AfterViews
    void initData() {

        if (intentByLogin) {
            splashShow = false;
            mSplashLayout.setVisibility(View.GONE);
            Injector.initMainActivityComponent().inject(this);
            routineCheckVersion();
        } else {
            handler.sendEmptyMessageDelayed(DELAY_CHECK_PHONE, 500);
//            checkPhoneState();
        }

        initLocationInfo();

        WebViewManager webViewManager = new WebViewManager(this, null, mWebView);
        webViewManager.init(mApiHelper, mCurrentUser);
        webViewManager.loadUrl("http://www.baidu.com");
        webViewManager.setLocationClient(locationClient);

        ApplicationHelper.getInstance().addActivity(this);
    }

    private void initLocationInfo() {
        //声明LocationClient类
        locationClient = new LocationClient(this);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        option.setScanSpan(0);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(false);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(true);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要

        locationClient.setLocOption(option);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (mDoubleClickExitDetector.click()) {
            ApplicationHelper.getInstance().exit();
            super.onBackPressed();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);  //这一句必须的，否则Intent无法获得最新的数据
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (mDownloadPermissionDialog != null) {
            mDownloadPermissionDialog.superDismiss();
            mDownloadPermissionDialog = null;
        }
        super.onDestroy();
    }

    private void routineCheckVersion() {
        long lastCheck = mSharedPreferencesHelper.getLong("checkUpdateTime", 0L);
        long now = System.currentTimeMillis();
        if (now - lastCheck > 60 * 60 * 1000) {    // 每1个小时检查一遍是否更新
            mSharedPreferencesHelper.setData("checkUpdateTime", now);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                        || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                        ) {

                    if (updatePermissionTip) {
                        requestPermissions(new String[]{
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        }, APP_PERMISSION);
                    }
                } else {
                    mApiHelper.getAppInfo(new GetAppInfoSubscriber());
                }
            } else {
                mApiHelper.getAppInfo(new GetAppInfoSubscriber());
            }
        }
    }

    private void checkPhoneState() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                    ) {
                if (phonePermissionTip) {
                    // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义)
                    requestPermissions(new String[]{
                            Manifest.permission.READ_PHONE_STATE,
                    }, APP_PERMISSION);
                }
            } else {
                checkNetwork();
            }
        } else {
            checkNetwork();
        }
    }

    void checkNetwork() {
        if (!Utils.Network.isNetworkAvailable()) {
            DialogUtils.showNoInternetDialog(this);
            return;
        }
        Injector.initMainActivityComponent().inject(this);
        handler.sendEmptyMessageDelayed(DELAY_TO_NEXT, 3000);
    }

    void delayToNextAction() {
//        mSplashLayout.setVisibility(View.GONE);
        String ticket = mSharedPreferencesHelper.getString(Constants.API.KEY_TICKET, "");
        if (TextUtils.isEmpty(ticket) || ticket.length() < 20) {
            IntentUtils.toLogin(MainActivity.this);
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mSplashLayout.setVisibility(View.GONE);
                }
            });
            splashShow = false;
            routineCheckVersion();
        }
    }

    private boolean showDownloadPermissionDialog() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    ) {

                BaseAnimatorSet bas_in = new FadeEnter();
                BaseAnimatorSet bas_out = new FadeExit();
                mDownloadPermissionDialog = new NormalDialog(this);

                mDownloadPermissionDialog.isTitleShow(false)
                        .btnNum(1)
                        .bgColor(Color.parseColor("#FFFFFF"))
                        .cornerRadius(5)
                        .content("应用自动升级功能无法使用!\n请在\"设置\"中开启存储卡权限")
                        .contentGravity(Gravity.CENTER)
                        .contentTextSize(13)
                        .contentTextColor(Color.parseColor("#333333"))
                        .dividerColor(Color.parseColor("#CCCCCC"))
                        .btnText("确定")
                        .btnTextSize(15.5f)
                        .btnTextColor(Color.parseColor("#0092FF"))
                        .widthScale(0.7f)
                        .showAnim(bas_in)
                        .dismissAnim(bas_out)
                        .show();

                mDownloadPermissionDialog.setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        mDownloadPermissionDialog.dismiss();
                    }
                });

                return true;
            }
        }
        return false;
    }

    private boolean showPhonePermissionDialog() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    ) {

                BaseAnimatorSet bas_in = new FadeEnter();
                BaseAnimatorSet bas_out = new FadeExit();
                mPhonePermissionDialog = new NormalDialog(this);

                mPhonePermissionDialog.isTitleShow(false)
                        .btnNum(1)
                        .bgColor(Color.parseColor("#FFFFFF"))
                        .cornerRadius(5)
                        .content("应用需要\"电话状态\"权限才能正常使用\n请在\"设置\"中开启权限")
                        .contentGravity(Gravity.CENTER)
                        .contentTextSize(13)
                        .contentTextColor(Color.parseColor("#333333"))
                        .dividerColor(Color.parseColor("#CCCCCC"))
                        .btnText("确定")
                        .btnTextSize(15.5f)
                        .btnTextColor(Color.parseColor("#0092FF"))
                        .widthScale(0.7f)
                        .showAnim(bas_in)
                        .dismissAnim(bas_out)
                        .show();

                mPhonePermissionDialog.setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        mPhonePermissionDialog.dismiss();
                    }
                });

                return true;
            }
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);


        if (splashShow) {
            phonePermissionTip = false;
        } else {
            updatePermissionTip = false;
        }

        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case APP_PERMISSION:
                boolean granted = true;
                for (int i : grantResults) {
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        granted = false;
                        break;
                    }
                }

                if (!granted) {
                    // 没有获取到权限，做特殊处理
                    if (splashShow) {
                        showPhonePermissionDialog();
                    } else {
                        showDownloadPermissionDialog();
                    }
                } else {
                    if (splashShow) {
                        checkNetwork();
                    } else {
                        mApiHelper.getAppInfo(new GetAppInfoSubscriber());
                    }
                }
                break;
            default:
                break;
        }
    }

    ApiHelper getApiHelper() {
        return mApiHelper;
    }

    CurrentUser getCurrentUser() {
        return mCurrentUser;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        boolean b = super.onTouchEvent(event);
        if (event.getAction() == MotionEvent.ACTION_MOVE) {
        }
        return super.onTouchEvent(event);
    }

    private class GetAppInfoSubscriber extends Subscriber<AppInfo> {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(mStrErrorApi);
        }

        @Override
        public void onNext(final AppInfo appInfo) {
            if (appInfo.checkState(MainActivity.this)) {
                mCurrentUser.setAppInfo(appInfo);

                if (appInfo.AppVersion > Utils.App.getAppVersionCode()) {
                    if (!showDownloadPermissionDialog()) {
                        DialogUtils.showUpdateDialog(MainActivity.this, appInfo.AppUrl, mSharedPreferencesHelper, appInfo.ForceUpdate);
                    }
                }
            } else {
                Utils.UI.showToastShort(mStrErrorApi);
            }
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == DELAY_CHECK_PHONE) {
                checkPhoneState();
            } else if (msg.what == DELAY_TO_NEXT) {
                delayToNextAction();
            }
        }
    };

}
